package com.dongqb.win;

import java.awt.AWTEvent;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import com.dongqb.bean.StockInfo;
import com.dongqb.common.CacheData;
import com.dongqb.common.WebUtil;

public class MainWinListener extends MainWin implements ActionListener, AWTEventListener {
	
	// 股票详情对话框
	public StockDialog dialog = new StockDialog();
	// 建议线程队列
	private SwingWorker<Void, List<String>> suggestionWorker;
	// 更新状态
	private volatile boolean isUpdating = false;
	// 添加成员变量
	private Timer suggestionTimer = new Timer(500, e -> { // 300ms延迟
		updateSuggestions();
	});

	public MainWinListener() {
		Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
		//设置任务不重复执行
		suggestionTimer.setRepeats(false);
		// 修改DocumentListener
		textField.getDocument().addDocumentListener(new DocumentListener() {
			public void changedUpdate(DocumentEvent e) {
				triggerUpdate();
			}

			public void insertUpdate(DocumentEvent e) {
				triggerUpdate();
			}

			public void removeUpdate(DocumentEvent e) {
				triggerUpdate();
			}

			private void triggerUpdate() {
				//重新启动任务
				suggestionTimer.restart();
			}
		});
		textField.addKeyListener(new KeyAdapter() {
		    public void keyPressed(KeyEvent e) {
		        if (e.getKeyCode() == KeyEvent.VK_DOWN && !suggestionPopup.isVisible()) {
		            suggestionPopup.show(textField, 0, textField.getHeight());
		            suggestionList.requestFocus();
		        }
		    }
		});

		// 列表选择事件
		suggestionList.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 1) {
					selectSuggestion();
				}
			}
		});

		suggestionList.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					selectSuggestion();
				}
			}
		});

		// 添加鼠标监听器
		jlist.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int index = jlist.locationToIndex(e.getPoint());
				 // 关键：获取该索引项的实际显示区域
		        Rectangle bounds = jlist.getCellBounds(index, index);
		        
		        // 判断点击点是否在该区域内
		        if (bounds != null && bounds.contains(e.getPoint())) {
		            // 点击的是真实的数据项
		            if (index != checkIdx) {
		                checkIdx = index;
		                dialog.loadData(listModel.get(index));
		                dialog.show(frame.getLocationOnScreen());
		            } else {
		                // 再次点击同一项，取消选中
		                checkIdx = -1;
		                jlist.clearSelection();
		                dialog.hide();
		            }
		        } else {
		            // 点击的是空白区域，清空选中
		            checkIdx = -1;
		            jlist.clearSelection();
		            dialog.hide();
		        }
			}
		});
		
		closeButton.addActionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource()==closeButton) {
			frame.setVisible(false);
			checkIdx = -1;
			jlist.clearSelection();
			dialog.hide();
		}
	}

	@Override
	public void eventDispatched(AWTEvent event) {
		// 键盘事件
		if (event.getClass() == KeyEvent.class) {
			KeyEvent ke = (KeyEvent) event;
			if (ke.getID() == KeyEvent.KEY_RELEASED) {
				int keycode = ke.getKeyCode();
				// 如果是删除按钮
				if (keycode == 127) {
					if (checkIdx >= 0) {
						StockInfo info = listModel.remove(checkIdx);
						CacheData.loadService.deleteData(info);
						checkIdx = -1;
						dialog.hide();
					}
				}
			}
		}
	}

	/**
	 * 更新搜索股票结果
	 */
	private void updateSuggestions() {
		final String text = textField.getText().trim();

		// 取消正在进行的worker
		if (suggestionWorker != null && !suggestionWorker.isDone()) {
			suggestionWorker.cancel(true);
		}

		if (text.isEmpty()) {
			suggestionPopup.setVisible(false);
			return;
		}

		// 创建新的worker
		suggestionWorker = new SwingWorker<Void, List<String>>() {
			@Override
			protected Void doInBackground() throws Exception {
				if (isUpdating)
					return null;
				isUpdating = true;

				List<String> suggestions = WebUtil.getSuggestLst(text);
				publish(suggestions);

				isUpdating = false;
				return null;
			}

			@Override
			protected void process(List<List<String>> chunks) {
				if (isCancelled() || chunks.isEmpty())
					return;

				List<String> suggestions = chunks.get(0);
				suggestionListModel.clear();

				for (String suggestion : suggestions) {
					suggestionListModel.addElement(suggestion);
				}

				if (suggestionListModel.isEmpty()) {
					suggestionPopup.setVisible(false);
				} else {
					suggestionList.setVisibleRowCount(Math.min(suggestionListModel.size(), 5));

					if (!suggestionPopup.isVisible()) {
						suggestionPopup.show(textField, 0, textField.getHeight());
					}

	                // 1. 设置 popup 宽度与 textField 一致
	                SwingUtilities.invokeLater(() -> {
	                    suggestionPopup.pack();
	                    suggestionPopup.setSize(textField.getWidth(), suggestionPopup.getPreferredSize().height);
	                });

	                // 2. 保持 textField 焦点
	                SwingUtilities.invokeLater(() -> textField.requestFocusInWindow());
				}
			}
		};

		suggestionWorker.execute();
	}

	/**
	 * 选中股票
	 */
	private void selectSuggestion() {
		String selected = suggestionList.getSelectedValue();
		if (selected != null) {
			textField.setText("");
			suggestionPopup.setVisible(false);
			textField.requestFocus();
			String[] str = selected.split(" ");
			boolean isexists=false;
			for(int i=0;i<listModel.size();i++) {
				if(listModel.get(i).getBh().equals(str[0])) {
					isexists=true;
					break;
				}
			}
			if (!isexists) {
				CacheData.loadService.insertData(str[1], str[0]);
				listModel.addElement(new StockInfo(str[1], str[0], null, null));
				CacheData.onTimeService.process();
			}
		}
	}

	/**
	 * 加载数据
	 */
	public void initData() {
		List<StockInfo> list = CacheData.loadService.loadData();
		if (list == null) {
			return;
		}
		for (StockInfo element : list) {
			listModel.addElement(element);
		}
		CacheData.onTimeService.process();
	}

	public void updateJlistModel() {
		if (jlist != null) {
			jlist.repaint();
		}
	}
}
